package ru.spb.osll.myfit.server.parser;

import ru.spb.osll.myfit.common.Define;
import ru.spb.osll.myfit.common.PageElement;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * User: Vassar
 * Date: 04.05.2011
 * Time: 11:18:24
 */
public class DefineElementParser implements IPageElementParser {
  private Pattern DEFINE_PATTERN1 = Pattern.compile(
    "!define\\s+((([\\w\\d]+\\.)?[\\w\\d]+)+)\\s+\\{([\\w\\W&&[^\\{\\}]]*)\\}\\s*");
  private Pattern DEFINE_PATTERN2 = Pattern.compile(
    "!define\\s+((([\\w\\d]+\\.)?[\\w\\d]+)+)\\s+\\[([\\w\\W&&[^\\[\\]]]*)\\]\\s*");
  private Pattern DEFINE_PATTERN3 = Pattern.compile(
    "!define\\s+((([\\w\\d]+\\.)?[\\w\\d]+)+)\\s+\\(([\\w\\W&&[^\\(\\)]]*)\\)\\s*");

  private int m_pattern;

  @Override
  public boolean matches(String line) {
    if (DEFINE_PATTERN1.matcher(line).matches()) {
      m_pattern = 1;
      return true;
    } else if (DEFINE_PATTERN2.matcher(line).matches()) {
      m_pattern = 2;
      return true;
    } else {
      m_pattern = 3;
      return DEFINE_PATTERN3.matcher(line).matches();
    }
  }

  @Override
  public PageElement parse(String line) {
    Matcher matcher;

    switch (m_pattern) {
      case 1:
        matcher = DEFINE_PATTERN1.matcher(line);
        break;
      case 2:
        matcher = DEFINE_PATTERN2.matcher(line);
        break;
      default:
        matcher = DEFINE_PATTERN3.matcher(line);
    }

    matcher.find();
    String name = matcher.group(1);
    String value = matcher.group(4);

    return new Define(name, value);
  }
}
